<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
               label-width="100px">
        <el-form-item label="分公司代码" prop="identityCode">
          <el-input
            v-model="queryParams.identityCode"
            placeholder="请输入分公司代码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!--        <el-form-item label="公司名称" prop="corporateName">-->
        <!--          <el-select v-model="queryParams.corporateName" filterable placeholder="请选择分公司名称">-->
        <!--            <el-option-->
        <!--              v-for="item in companyList"-->
        <!--              :key="item.id"-->
        <!--              :label="item.corporateName"-->
        <!--              :value="item.corporateName"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:branchOffice:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:branchOffice:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:branchOffice:remove']"
          >删除
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="branchList" @selection-change="handleSelectionChange" border stripe>
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="分公司代码" align="center" prop="identityCode"/>
        <!--        <el-table-column label="用户名" align="center" prop="userName"/>-->
        <!--        <el-table-column label="分销名额" align="center" prop="bonusPool"/>-->
        <!--        <el-table-column label="电子邮箱" align="center" prop="email"/>-->
        <!--        <el-table-column label="手机号码" align="center" prop="phonenumber"/>-->
        <el-table-column label="法人姓名" align="center" prop="legalPerson"/>
        <el-table-column label="公司名称" align="center" prop="corporateName" width="120"/>
        <el-table-column label="信用代码" align="center" prop="creditCode" width="120"/>
        <el-table-column label="经营城市" align="center" prop="manageCity" width="120"/>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </el-row>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="branchForm" :model="branchForm" :rules="branchRules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名：" prop="userName">
              <el-input v-model="branchForm.userName" placeholder="请输入用户名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱：" prop="email">
              <el-input v-model="branchForm.email" placeholder="请输入电子邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码：" prop="phonenumber">
              <el-input v-model="branchForm.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人姓名：" prop="legalPerson">
              <el-input v-model="branchForm.legalPerson" placeholder="请输入法人姓名"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司名称：" prop="corporateName">
              <el-input v-model="branchForm.corporateName" placeholder="请输入公司名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信用代码：" prop="creditCode">
              <el-input v-model="branchForm.creditCode" placeholder="请输入信用代码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!branchForm.distributionUserId">
          <el-col :span="12">
            <el-form-item label="密码：" prop="password">
              <el-input v-model="branchForm.password" placeholder="请输入密码" type="password" maxlength="20"
                        show-password/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码：" prop="surePassword">
              <el-input v-model="branchForm.surePassword" placeholder="请输入确认密码" type="password" maxlength="20"
                        show-password/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="!branchForm.distributionUserId">
            <el-form-item label="直推分公司：" prop="parentId">
              <el-select v-model="branchForm.parentId" filterable placeholder="请选择分公司名称">
                <el-option
                  v-for="item in companyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经营城市：" prop="manageCity">
              <el-cascader
                v-model="branchForm.manageCity"
                :options="manageCityList"
                :props="{ expandTrigger:'click',value:'id',label:'city',multiple:true }"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分销类型：" prop="isDistribution">
              <el-switch
                v-model="branchForm.isDistribution"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value=1
                inactive-value=0
                active-text="参与分销"
                inactive-text="不参与分销">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="营业执照：" prop="businessLicense">
              <image-upload v-model="branchForm.businessLicense" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人身份证：" prop="legalIdCard">
              <image-upload v-model="branchForm.legalIdCard" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上传证书：" prop="certificate">
              <image-upload v-model="branchForm.certificate" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传合同：" prop="contract">
              <image-upload v-model="branchForm.contract" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addBranchInfo, queryBranchList, queryProviceList, queryBranchInfo, editBranchInfo, deleteBranchInfo
} from "@/api/organize/branch";
import {queryCompanyList} from "@/api/organize/agent";

export default {
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.branchForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      loading: true,// 遮罩层
      ids: [], // 选中数组
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      showSearch: true, // 显示搜索条件
      total: 0,// 总条数
      companyList: [],//分公司列表
      branchList: [],
      title: "",// 弹出层标题
      open: false,// 是否显示弹出层
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        identityCode: "",
        corporateName: ""
      },
      // 表单校验
      branchRules: {
        userName: [
          {required: true, message: "用户名称不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        legalPerson: [{required: true, message: "法人姓名不能为空", trigger: "blur"}],
        corporateName: [{required: true, message: "公司名称不能为空", trigger: "blur"}],
        creditCode: [{required: true, message: "信用代码不能为空", trigger: "blur"}],
        manageCity: [{required: true, message: "经营城市不能为空", trigger: "change"}],
        contract: [{message: "合同不能为空", trigger: "change"}],
        certificate: [{message: "证书不能为空", trigger: "change"}],
        // legalIdCard: [{required: true, message: "法人身份证不能为空", trigger: "change"}],
        // businessLicense: [{required: true, message: "营业执照不能为空", trigger: "change"}],
        password: [{required: true, message: "用户密码不能为空", trigger: "blur"},
          {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'}],
        surePassword: [{required: true, message: "确认密码不能为空", trigger: "blur"},
          {validator: equalToPassword, required: true, trigger: "blur"},],
        email: [{required: true, type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}],
        phonenumber: [{
          required: true,
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur"
        }]
      },
      branchForm: {},// 分公司表单信息
      manageCityList: [],//城市列表
    };
  },
  created() {
    this.getList();
    this.getCityList()
    this.getCompanyList()
  },
  methods: {
    /** 查询分公司列表 */
    getList() {
      this.loading = true;
      queryBranchList(this.queryParams).then(response => {
          this.branchList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 查询分公司和总公司列表
    getCompanyList() {
      this.loading = true;
      queryCompanyList(this.queryParams).then(response => {
          this.companyList = response;
          // this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询城市列表 */
    getCityList() {
      this.loading = true;
      queryProviceList().then(response => {
          let list = response.rows
          let newList = []
          for (let i = 0; i < list.length; i++) {
            newList.push({
              city: list[i].province,
              id: list[i].id,
              children: list[i].cities
            })
          }
          this.manageCityList = newList
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.branchForm = {
        corporateName: undefined,//公司名称
        legalPerson: undefined,//法人姓名
        userName: undefined,
        creditCode: undefined,//信用代码
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        manageCity: undefined,//经营城市
        identityCode: "",//公司代码
        legalIdCard: '',//身份证正反面
        contract: "",//合同
        certificate: undefined,//证书
        postIds: [],
        roleIds: [],
        isDistribution: undefined
      };
      this.resetForm("branchForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加分公司";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      queryBranchInfo(row.distributionUserId).then(response => {
        this.branchForm = response.data;
        this.branchForm.manageCity = JSON.parse(response.data.manageCity)
        // this.branchForm.userId = response.data.userId
        this.open = true;
        this.title = "修改分公司信息";
        // this.branchForm.password = "";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["branchForm"].validate(valid => {
        // console.log("分销:"+ this.branchForm.isDistribution);
        if (valid) {
          let cardIdList = this.branchForm.legalIdCard.split(';')
          // if (cardIdList && cardIdList.length != 2) {
          //   this.$message.error('身份证照片数量不正确！')
          //   return
          // }
          // this.branchForm.legalIdCard = this.branchForm.legalIdCard.toString()
          this.branchForm.manageCity = JSON.stringify(this.branchForm.manageCity)
          let data = {
            distributionUser: this.branchForm,
            distributionUserBasicInfo: this.branchForm,
            user: {
              phonenumber: this.branchForm.phonenumber,
              email: this.branchForm.email,
              password: this.branchForm.password,
              surePassword: this.branchForm.surePassword,
              userName: this.branchForm.userName,
              // userId: this.branchForm.userId
            },
            // 需要检查，获取不到
            isDistribution: this.branchForm.isDistribution,
            // 固定模式分销，暂不考虑自定义
            distributionMode: 0
          }
          if (this.branchForm.distributionUserId) {
            editBranchInfo(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBranchInfo(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log('this.ids', this.ids)
      const ids = row.id || this.ids.toString();
      this.$modal.confirm('是否确认删除？').then(function () {
        return deleteBranchInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
